package com.xjy.spring.thrift.core;

import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TTransportException;
import com.xjy.spring.thrift.config.ThriftServerConfig;
import com.xjy.spring.thrift.zk.ThriftServiceRegister;
import com.xjy.spring.thrift.zk.ZKConstant;

public class ThreadPoolThriftServer extends AbstractThriftServer {

    @Override
    protected void startThriftServer(TProcessor tProcessor, ThriftServerConfig config) throws TTransportException {
        System.err.println("start server, type is ThreadPool, config is " + config);
        TServerSocket serverTransport = new TServerSocket(config.getPort());
        TThreadPoolServer.Args ttpsArgs = new TThreadPoolServer.Args(serverTransport);
        ttpsArgs.processor(tProcessor);
        ttpsArgs.protocolFactory(new TBinaryProtocol.Factory());
        // 线程池服务模型，使用标准的阻塞式IO，预先创建一组线程处理请求。
        TServer server = new TThreadPoolServer(ttpsArgs);
        // 此处会阻塞
        server.serve();

    }

    @Override
    protected void registerThriftServer(ThriftServerConfig config) {
        new ThriftServiceRegister(ZKConstant.CONNECT_STRING,
                ZKConstant.SESSION_TIMEOUT, ZKConstant.CONNECTION_TIMEOUT)
                .register(config, ZKConstant.ROOT_PATH,
                        ZKConstant.THRIFT_SERVICE_PATH);
    }
}
